<?php

namespace App\Http\Requests;

use App\Models\District;
use App\User;
use Illuminate\Foundation\Http\FormRequest;

class UserAddressRequest extends FormRequest
{
    use CheckDistrict;
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return $this->get('uid') == \Auth::id();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $districtTable = (new District())->getTable();
        return [
            'province_code' => "exists:$districtTable",
            'city_code' => "exists:$districtTable",
            'district_code' => "exists:$districtTable",
            'phone' => 'phone',
            'address' => 'required',
        ];
    }

    public function validator()
    {
        $validator = \Validator::make($this->all(), [
            'phone' => 'required|phone',
            'address' => 'required',
        ]);
        $validator->after(function ($validator) {
            $checkDistrictResult = $this->checkDistrict();
            if ($checkDistrictResult['ret'] != 0) {
                $validator->errors()->add('district', $checkDistrictResult['msg']);
            }
        });
        return $validator;

    }

}
